package com.tl.sun.module.update;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.tl.sun.AppContext;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.helper.UIHelper;
import com.tl.sun.model.BaseModel;
import com.tl.sun.model.UpdateEntity;
import com.tl.sun.model.UpdateInfo;
import com.tl.sun.utils.ToastUtil;
import com.tl.sun.utils.common.AppUtils;
import com.tl.sun.utils.common.DeviceUtils;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;


/**
 * 更新管理类
 *
 * @author FireAnt（http://my.oschina.net/LittleDY）
 * @version 创建时间：2014年11月18日 下午4:21:00
 */

public class UpdateManager {

    private UpdateInfo mUpdate;

    private Context mContext;

    private boolean isShow = false;

    private boolean isForceUpdate;

    private ProgressDialog _waitDialog;


    public UpdateManager(Context context, boolean isShow) {
        this.mContext = context;
        this.isShow = isShow;
    }


    private void getAppInit() {
        int curVersionCode = AppUtils.getAppInfo(mContext.getApplicationContext()).getVersionCode();

//        String snValue = PhoneUtils.getPhoneIMEI(mContext);

        HashMap<String, String> map = new HashMap<>();
        map.put("type", "open");
        map.put("version", curVersionCode + "");
        map.put("platform", "android");
        map.put("oem", DeviceUtils.getManufacturer());
//        map.put("sn", snValue);
        map.put("info", DeviceUtils.getModel());
        map.put("proxy", "0");

        JSONObject jsonObject = new JSONObject(map);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(mContext)).post(AppContext.getInstance().getBaseUrl()+"client/check_update")
                .tag(mContext)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {
                            if (baseModel.getCode().equals("1")) {

                                Type versionType = new TypeToken<BaseModel<UpdateEntity>>() {
                                }.getType();
                                BaseModel<UpdateEntity> versionInfo;
                                try {
                                    versionInfo = gson.fromJson(s, versionType);
                                    UpdateEntity updateEntity = versionInfo.getData();
                                    mUpdate = new UpdateInfo();
                                    mUpdate.setDownloadUrl(updateEntity.getDownloadUrl());
                                    mUpdate.setUpdateLogo(updateEntity.getDesc());
                                    isForceUpdate = updateEntity.isForce();
                                } catch (JsonSyntaxException e) {
                                    versionInfo = gson.fromJson(s, BaseModel.class);
                                }

                                showUpdateInfo();
                            } else if (baseModel.getCode().equals("3") && isShow) {
                                ToastUtil.showToast("已经是最新版本了");
                            }

                        } else {
                            ToastUtil.showToast("出错了");
                        }

                    }
                });

    }


    public boolean haveNew() {
        if (this.mUpdate == null) {
            return false;
        }
        boolean haveNew = false;
        int curVersionCode = AppUtils.getAppInfo(AppContext.getInstance()).getVersionCode();
        if (curVersionCode < mUpdate.getVersionCode()) {
            haveNew = true;
        }
        return haveNew;
    }

    public void checkUpdate() {
        if (isShow) {
            showCheckDialog();
        }

        getAppInit();

    }


//    private void onFinshCheck() {
//        if (haveNew()) {
//            showUpdateInfo();
//        } else {
//            if (isShow) {
//                ToastUtil.showToast("已经是最新版本");
//            }
//        }
//    }

    private void onFinshCheck() {
        if (haveNew()) {
            showUpdateInfo();
        } else {
            if (isShow) {
                ToastUtil.showToast("已经是最新版本");
            }
        }
    }

    private void showCheckDialog() {
//        if (_waitDialog == null) {
//            _waitDialog = DialogHelp.getWaitDialog((Activity) mContext, "正在获取新版本信息...");
//        }
//        _waitDialog.show();
    }

    private void hideCheckDialog() {
        if (_waitDialog != null) {
            _waitDialog.dismiss();
        }
    }


    private void showUpdateInfo() {
        if (mUpdate == null) {
            return;
        }

        String updateLogo = mUpdate.getUpdateLogo().replace("|", "\n");

        final Dialog updateDialog = new Dialog(mContext);
        updateDialog.setContentView(R.layout.dialog_update);
        updateDialog.setCancelable(false);
        TextView updateContent = (TextView) updateDialog.findViewById(R.id.update_content);
        updateContent.setText(updateLogo);
        TextView confirmBtn = (TextView) updateDialog.findViewById(R.id.confirm_text);
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UIHelper.openDownLoadService(mContext, mUpdate.getDownloadUrl(), AppContext.version);
                updateDialog.dismiss();
            }
        });

        if (!isForceUpdate) {

        }
        updateDialog.show();


    }


//    private void showLatestDialog() {
//        final OutDialog outDialog = new OutDialog((Activity) mContext, "提示信息", "已经是最新版本了", 1);
//        outDialog.setPositiveButton(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                outDialog.close();
//            }
//        });
//    }

//    private void showFaileDialog() {
//        final OutDialog outDialog = new OutDialog((Activity) mContext, "提示信息", "网络异常，无法获取新版本信息", 1);
//        outDialog.setPositiveButton(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                outDialog.close();
//            }
//        });
//    }
}
